package com.azkj.album.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.azkj.album.R;
import com.azkj.album.dto.FakeModel;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.view.widgets.staggedrv.StaggedAdapter;

import java.util.List;

public class MainAdapter extends StaggedAdapter<FakeModel> {
    private Context mContext;

    private boolean isDeleteMode;

    public MainAdapter(Context c, List<FakeModel> list) {
        super(c);
        this.mContext = c;
        datas = list;
    }


    @Override
    public RecyclerView.ViewHolder addViewHolder(ViewGroup viewGroup, int i) {
        //绑定自定义的viewholder
        View v = LayoutInflater.from(mContext).inflate(R.layout.item_main_list, viewGroup, false);
        return new MyHolder(v);
    }

    @Override
    public void bindView(RecyclerView.ViewHolder viewHolder, int i) {

        MyHolder myHolder = (MyHolder) viewHolder;
        FakeModel model = datas.get(i);

        // 在加载图片之前设定好图片的宽高，防止出现item错乱及闪烁
        ViewGroup.LayoutParams layoutParams = myHolder.img.getLayoutParams();
        layoutParams.height = model.getHeight();
        myHolder.img.setLayoutParams(layoutParams);

        myHolder.img.setImageResource(model.getResourceId());

        myHolder.rl_content.setOnClickListener(v -> {
            if (isDeleteMode) {
                model.setCheck(!model.isCheck());
                myHolder.rl_del.setVisibility(model.isCheck() ? View.VISIBLE : View.GONE);
                myHolder.tv_del_num.setText(String.valueOf(getCheckedNum()));
            } else {
                ToastUtils.showCenterToast("item clicked:" + i);
            }

        });

    }

    public int getCheckedNum() {
        int num = 0;
        for (FakeModel model : datas) {
            if (model.isCheck()) num++;
        }
        return num;
    }

    public void setDeleteMode(boolean deleteMode) {
        this.isDeleteMode = deleteMode;
    }

    public void resetCheck() {
        for (FakeModel model : datas) {
            model.setCheck(false);
        }
    }
}


/**
 * 自定义viewholder
 */

class MyHolder extends RecyclerView.ViewHolder {

    ImageView img;
    View rl_content;
    View rl_del;
    TextView tv_del_num;

    public MyHolder(@NonNull View itemView) {
        super(itemView);

        img = itemView.findViewById(R.id.img);
        rl_content = itemView.findViewById(R.id.rl_content);
        rl_del = itemView.findViewById(R.id.rl_del);
        tv_del_num = itemView.findViewById(R.id.tv_del_num);

    }
}